#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简单计算器测试脚本
直接执行计算操作并记录到日志
"""

import math
import logging
import time
import sys

# 配置日志 - 追加到calculator.log文件
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('calculator.log', encoding='utf-8', mode='a')
    ]
)
logger = logging.getLogger('CalculatorMCP')

def add(a, b):
    """加法运算"""
    start_time = time.time()
    try:
        result = float(a) + float(b)
        logger.info(f"加法运算: {a} + {b} = {result}")
        execution_time = time.time() - start_time
        logger.info(f"函数 add 执行时间: {execution_time:.4f}秒")
        return result
    except Exception as e:
        logger.error(f"加法运算失败: {e}")
        raise

def subtract(a, b):
    """减法运算"""
    start_time = time.time()
    try:
        result = float(a) - float(b)
        logger.info(f"减法运算: {a} - {b} = {result}")
        execution_time = time.time() - start_time
        logger.info(f"函数 subtract 执行时间: {execution_time:.4f}秒")
        return result
    except Exception as e:
        logger.error(f"减法运算失败: {e}")
        raise

def multiply(a, b):
    """乘法运算"""
    start_time = time.time()
    try:
        result = float(a) * float(b)
        logger.info(f"乘法运算: {a} × {b} = {result}")
        execution_time = time.time() - start_time
        logger.info(f"函数 multiply 执行时间: {execution_time:.4f}秒")
        return result
    except Exception as e:
        logger.error(f"乘法运算失败: {e}")
        raise

def divide(a, b):
    """除法运算"""
    start_time = time.time()
    try:
        if float(b) == 0:
            raise ValueError("除数不能为零")
        result = float(a) / float(b)
        logger.info(f"除法运算: {a} ÷ {b} = {result}")
        execution_time = time.time() - start_time
        logger.info(f"函数 divide 执行时间: {execution_time:.4f}秒")
        return result
    except Exception as e:
        logger.error(f"除法运算失败: {e}")
        raise

def calculate_expression(expression):
    """计算数学表达式"""
    start_time = time.time()
    try:
        # 创建安全的计算环境
        safe_dict = {
            "__builtins__": {},
            "abs": abs, "round": round, "min": min, "max": max,
            "sum": sum, "pow": pow,
            "sin": math.sin, "cos": math.cos, "tan": math.tan,
            "sqrt": math.sqrt, "log": math.log, "exp": math.exp,
            "pi": math.pi, "e": math.e
        }
        
        result = eval(expression, safe_dict)
        logger.info(f"表达式计算: {expression} = {result}")
        execution_time = time.time() - start_time
        logger.info(f"函数 calculate 执行时间: {execution_time:.4f}秒")
        return result
    except Exception as e:
        logger.error(f"表达式计算失败: {e}")
        raise

def parse_expression(expr):
    """解析数学表达式"""
    expr = expr.strip().replace(' ', '')
    
    # 检查是否为简单的二元运算（只有一个运算符）
    operators = ['+', '-', '*', '/']
    operator_count = sum(1 for op in operators if op in expr)
    
    # 特殊处理：如果表达式以负号开头，不计算为运算符
    if expr.startswith('-'):
        operator_count -= 1
    
    # 如果只有一个运算符，使用简单解析
    if operator_count == 1:
        # 处理加法
        if '+' in expr:
            idx = expr.rfind('+')
            if idx > 0:
                left = expr[:idx]
                right = expr[idx+1:]
                return add(left, right)
        
        # 处理减法（不是开头的负号）
        elif '-' in expr and not expr.startswith('-'):
            idx = expr.rfind('-')
            if idx > 0:
                left = expr[:idx]
                right = expr[idx+1:]
                return subtract(left, right)
        
        # 处理乘法
        elif '*' in expr:
            idx = expr.rfind('*')
            if idx > 0:
                left = expr[:idx]
                right = expr[idx+1:]
                return multiply(left, right)
        
        # 处理除法
        elif '/' in expr:
            idx = expr.rfind('/')
            if idx > 0:
                left = expr[:idx]
                right = expr[idx+1:]
                return divide(left, right)
    
    # 复杂表达式或单个数字使用eval
    return calculate_expression(expr)

if __name__ == "__main__":
    logger.info("简单计算器启动")
    
    if len(sys.argv) > 1:
        # 从命令行参数获取表达式
        expression = ' '.join(sys.argv[1:])
    else:
        # 从标准输入读取
        try:
            expression = input().strip()
        except EOFError:
            expression = None
    
    if expression:
        try:
            result = parse_expression(expression)
            print(f"{expression} = {result}")
        except Exception as e:
            print(f"计算错误: {e}")
            logger.error(f"计算错误: {e}")
    else:
        print("请输入数学表达式")